package slidingWindowAlgorithm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Class438 {

        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> res =  new ArrayList<>();
            int sizeS = s.length(), sizeT = p.length();

            if(sizeS < sizeT) return res;


            Map<Character, Integer> need = new HashMap<>();
            for(char c : p.toCharArray())
                need.put(c, need.getOrDefault(c, 0) + 1);



            int valid = 0;
            int needSize = need.size();
            Map<Character, Integer> window = new HashMap<>();
            int left = 0, right = 0;

            while(right < sizeS) {
                char c = s.charAt(right);
                right++;
                if(need.containsKey(c)) {
                    window.put(c, window.getOrDefault(c, 0) + 1);
                    if(window.get(c).equals(need.get(c)))
                        valid++;
                }

                while(valid == needSize) {
                    if(right - left == sizeT) {
                        res.add(left);
                    }
                    c = s.charAt(left);
                    left++;
                    if(need.containsKey(c)) {
                        if(window.get(c).equals(need.get(c)))
                            valid--;
                        window.put(c, window.get(c) - 1);
                    }
                }
            }

            return res;
        }

    public static void main(String[] args) {

        Class438 class438 = new Class438();
//        System.out.println(class438.findAnagrams("cbaebabacd", "abc"));
         List<Integer>  list= class438.findAnagrams("cbaebabacd", "abc");
        for (int a:list
             ) {
            System.out.println(a);

        }



    }


    }





